<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Java,数据库,JDBC," />










<meta name="description" content="摘要">
<meta property="og:type" content="article">
<meta property="og:title" content="JDBC">
<meta property="og:url" content="http://gushihu1.com/2020/03/01/JDBC/index.html">
<meta property="og:site_name" content="孤失狐的博客">
<meta property="og:description" content="摘要">
<meta property="article:published_time" content="2020-03-01T12:28:15.000Z">
<meta property="article:modified_time" content="2020-03-08T13:14:44.409Z">
<meta property="article:author" content="孤失狐">
<meta property="article:tag" content="Java">
<meta property="article:tag" content="数据库">
<meta property="article:tag" content="JDBC">
<meta name="twitter:card" content="summary">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://gushihu1.com/2020/03/01/JDBC/"/>





  <title>JDBC | 孤失狐的博客</title>
  








  <script type="text/javascript" src="//libs.baidu.com/jquery/1.8.3/jquery.min.js"></script>
<meta name="generator" content="Hexo 4.2.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">
  <!-- 雪花特效 -->
  <script type="text/javascript">
  var windowWidth = $(window).width();
  if (windowWidth > 480) {
    document.write('<script type="text/javascript" src="/js/src/snow.js"><\/script>');
  }
  </script>

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">孤失狐的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">勿忘初心</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off"
             placeholder="搜索..." spellcheck="false"
             type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://gushihu1.com/2020/03/01/JDBC/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="孤失狐">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/ChatHead.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="孤失狐的博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JDBC</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-03-01T20:28:15+08:00">
                2020-03-01
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index">
                    <span itemprop="name">Java</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h3 id="摘要"><a href="#摘要" class="headerlink" title="摘要"></a>摘要</h3><a id="more"></a>

<h1 id="JDBC"><a href="#JDBC" class="headerlink" title="JDBC"></a>JDBC</h1><h2 id="1-1获取连接"><a href="#1-1获取连接" class="headerlink" title="1.1获取连接"></a>1.1获取连接</h2><ul>
<li>数据库url:     ==url=“ jdbc:mysql://localhost:3306/数据库名 ”==</li>
<li>配置信息<ul>
<li>用户名：</li>
<li>密码：</li>
</ul>
</li>
<li>驱动</li>
</ul>
<h3 id="1-1-1-配置文件获取连接"><a href="#1-1-1-配置文件获取连接" class="headerlink" title="1.1.1 配置文件获取连接"></a>1.1.1 配置文件获取连接</h3><figure class="highlight properties"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="attr">url</span>=<span class="string">jdbc:mysql://localhost/testjdbc?serverTimezone=UTC</span></span><br><span class="line"><span class="attr">username</span>=<span class="string">root</span></span><br><span class="line"><span class="attr">password</span>=<span class="string">admin</span></span><br><span class="line"><span class="attr">driverClassName</span>=<span class="string">com.mysql.cj.jdbc.Driver</span></span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title">getConnection1</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        <span class="comment">//1.读取配置文件中的四个基本信息</span></span><br><span class="line">        InputStream is = GetConnection1.class.getClassLoader().getResourceAsStream("配置文件路径");</span><br><span class="line">        Properties pros =<span class="keyword">new</span> Properties();</span><br><span class="line">        pros.load(is);</span><br><span class="line">        String user = pros.getProperty(<span class="string">"user"</span>);</span><br><span class="line">        String password = pros.getProperty(<span class="string">"password"</span>);</span><br><span class="line">        String url = pros.getProperty(<span class="string">"url"</span>);</span><br><span class="line">        String driverClass = pros.getProperty(<span class="string">"driverClass"</span>);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2.加载驱动</span></span><br><span class="line">        Class.forName(driverClass);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3.获取连接</span></span><br><span class="line">        Connection conn = DriverManager.getConnection(url,user,password);</span><br><span class="line">    	<span class="keyword">return</span> conn;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-2-关闭资源"><a href="#1-2-关闭资源" class="headerlink" title="1.2 关闭资源"></a>1.2 关闭资源</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">closeResource1</span><span class="params">(Connection conn, Statement ps,ResultSet rs)</span>  </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> ((ps != <span class="keyword">null</span>))&#123;</span><br><span class="line">                ps.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">catch</span> (SQLException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (conn != <span class="keyword">null</span>)&#123;</span><br><span class="line">                conn.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">catch</span> (SQLException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">if</span> (rs != <span class="keyword">null</span>)&#123;</span><br><span class="line">                rs.close();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;<span class="keyword">catch</span> (SQLException e)&#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-3-PreparedStatement和Statement"><a href="#1-3-PreparedStatement和Statement" class="headerlink" title="1.3 PreparedStatement和Statement"></a>1.3 PreparedStatement和Statement</h2><h3 id="1-3-1-Statement存在的问题"><a href="#1-3-1-Statement存在的问题" class="headerlink" title="1.3.1 Statement存在的问题"></a>1.3.1 Statement存在的问题</h3><ul>
<li>需要拼写SQL语句</li>
<li>存在SQL注入问题</li>
</ul>
<h3 id="1-3-2-Statement对数据库进行操作"><a href="#1-3-2-Statement对数据库进行操作" class="headerlink" title="1.3.2 Statement对数据库进行操作"></a>1.3.2 Statement对数据库进行操作</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">String user = <span class="string">"张三"</span>;</span><br><span class="line">String password = <span class="string">"zhangsan"</span>;</span><br><span class="line">String sql = <span class="string">"SELECT USER,PASSWORD FROM user_table WHERE USER = '"</span>+user+<span class="string">"' AND PASSWORD = '"</span>+password+<span class="string">"'"</span>;</span><br></pre></td></tr></table></figure>

<h3 id="1-3-3-PreparedStatement对数据库进行操作"><a href="#1-3-3-PreparedStatement对数据库进行操作" class="headerlink" title="1.3.3 PreparedStatement对数据库进行操作"></a>1.3.3 PreparedStatement对数据库进行操作</h3><h4 id="1-3-3-1-增删改"><a href="#1-3-3-1-增删改" class="headerlink" title="1.3.3.1 增删改"></a>1.3.3.1 增删改</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//4.预编译SQL语句，</span></span><br><span class="line">        String sql = <span class="string">"insert into customers(name,email,birth)values(?,?,?)"</span>;</span><br><span class="line">        PreparedStatement ps = conn.prepareStatement(sql);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//5.填充占位符</span></span><br><span class="line">        ps.setString(<span class="number">1</span>,<span class="string">"哪吒"</span>);</span><br><span class="line">        ps.setString(<span class="number">2</span>,<span class="string">"nezha@qq.com"</span>);</span><br><span class="line">        SimpleDateFormat sdf = <span class="keyword">new</span> SimpleDateFormat(<span class="string">"yyyy-MM-dd"</span>);</span><br><span class="line">        java.util.Date date = sdf.parse(<span class="string">"1000-01-01"</span>);</span><br><span class="line">        ps.setDate(<span class="number">3</span>, <span class="keyword">new</span> Date(date.getTime()));</span><br><span class="line"></span><br><span class="line">        <span class="comment">//6.执行操作</span></span><br><span class="line">        ps.execute();</span><br><span class="line"></span><br><span class="line">		<span class="comment">//7.资源的关闭</span></span><br><span class="line">        ps.close();</span><br><span class="line">        conn.close();</span><br></pre></td></tr></table></figure>

<h4 id="1-3-3-2-通用的增删改"><a href="#1-3-3-2-通用的增删改" class="headerlink" title="1.3.3.2 通用的增删改"></a>1.3.3.2 通用的增删改</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">PreparedStatementTest</span><span class="params">()</span></span>&#123;</span><br><span class="line">        String sql = <span class="string">"delete from customers where id = ?"</span>;</span><br><span class="line">        update(sql,<span class="number">3</span>,...);<span class="comment">//有几个问号，写几个参数</span></span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">update</span><span class="params">(String sql, Object ...args)</span> </span>&#123;</span><br><span class="line">        Connection connection = <span class="keyword">null</span> ;</span><br><span class="line">        PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//1.连接数据库</span></span><br><span class="line">            connection = getConnection1();</span><br><span class="line">            <span class="comment">//2.预编译的SQL语句，返回PreparedStatement实例</span></span><br><span class="line">            preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">            <span class="comment">//3.填充占位符</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length;i++)&#123;</span><br><span class="line">                preparedStatement.setObject(i + <span class="number">1</span>,args[i]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//4.执行</span></span><br><span class="line">            preparedStatement.execute();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="comment">//5.关闭资源</span></span><br><span class="line">            closeResource1(connection,preparedStatement,<span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h4 id="1-3-3-3-通用查询"><a href="#1-3-3-3-通用查询" class="headerlink" title="1.3.3.3 通用查询"></a>1.3.3.3 通用查询</h4><h5 id="1-3-3-3-1-返回表中的一条数据"><a href="#1-3-3-3-1-返回表中的一条数据" class="headerlink" title="1.3.3.3.1 返回表中的一条数据"></a>1.3.3.3.1 返回表中的一条数据</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">StatementTest st = <span class="keyword">new</span> StatementTest();</span><br><span class="line">      String sql = <span class="string">"select id,name,email from customers where id=?"</span>;</span><br><span class="line">      Customer customer = st.query1(Customer<span class="class">.<span class="keyword">class</span>, <span class="title">sql</span>, 2)</span>;</span><br><span class="line">      System.out.println(customer);</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">T  <span class="title">query1</span><span class="params">(Class&lt;T&gt; clazz,String sql,Object...args)</span> </span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">       ResultSet resultSet = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           connection = getConnection1();</span><br><span class="line">           preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">           <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length; i++)&#123;</span><br><span class="line">               preparedStatement.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">           &#125;</span><br><span class="line">           resultSet = preparedStatement.executeQuery();</span><br><span class="line">           <span class="comment">//获取结果集的数据元</span></span><br><span class="line">           ResultSetMetaData resultSetMetaData = resultSet.getMetaData();</span><br><span class="line">           <span class="comment">//获取结果集的列数</span></span><br><span class="line">           <span class="keyword">int</span> columnCount = resultSetMetaData.getColumnCount();</span><br><span class="line">           <span class="keyword">if</span> (resultSet.next())&#123;</span><br><span class="line">               T t = clazz.newInstance();</span><br><span class="line">               <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; columnCount;i++) &#123;</span><br><span class="line">                   <span class="comment">//获取列值</span></span><br><span class="line">                   Object columvalue = resultSet.getObject(i + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">                   <span class="comment">//获取某个列的列名</span></span><br><span class="line">                   String columnName = resultSetMetaData.getColumnName(i+<span class="number">1</span>);</span><br><span class="line">                   <span class="comment">//给customer对象指定的某个属性，赋值为value</span></span><br><span class="line">                   <span class="comment">//给customer对象指定的columnName属性，赋值为columvalues,通过反射</span></span><br><span class="line">                   Field field = clazz.getDeclaredField(columnName);</span><br><span class="line">                   field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                   field.set(t,columvalue);</span><br><span class="line">               &#125;</span><br><span class="line">               <span class="keyword">return</span> t;</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           closeResource1(connection,preparedStatement,resultSet);</span><br><span class="line"></span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h5 id="1-3-3-3-2-返回多行数据"><a href="#1-3-3-3-2-返回多行数据" class="headerlink" title="1.3.3.3.2 返回多行数据"></a>1.3.3.3.2 返回多行数据</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">StatementTest st = <span class="keyword">new</span> StatementTest();</span><br><span class="line">      String sql = <span class="string">"select id,name,birth from student where id&lt;?"</span>;</span><br><span class="line">      List&lt;Student&gt; list = st.query2(Student<span class="class">.<span class="keyword">class</span>, <span class="title">sql</span>, 4)</span>;</span><br><span class="line">      list.forEach(System.out::println);</span><br></pre></td></tr></table></figure>

<h5 id="1-3-3-3-3-查所有"><a href="#1-3-3-3-3-查所有" class="headerlink" title="1.3.3.3.3 查所有"></a>1.3.3.3.3 查所有</h5><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">StatementTest st &#x3D; new StatementTest();</span><br><span class="line">      String sql &#x3D; &quot;select id,name,birth from student &quot;;</span><br><span class="line">      List&lt;Student&gt; list &#x3D; st.query2(Student.class, sql);</span><br><span class="line">      list.forEach(System.out::println);</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> &lt;T&gt; <span class="function">List&lt;T&gt; <span class="title">query2</span><span class="params">(Class&lt;T&gt; clazz, String sql, Object...args)</span> </span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">       ResultSet resultSet = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           connection = getConnection1();</span><br><span class="line">           preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">           <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length; i++)&#123;</span><br><span class="line">               preparedStatement.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">           &#125;</span><br><span class="line">           resultSet = preparedStatement.executeQuery();</span><br><span class="line">           <span class="comment">//获取结果集的数据元</span></span><br><span class="line">           ResultSetMetaData resultSetMetaData = resultSet.getMetaData();</span><br><span class="line">           <span class="comment">//获取结果集的列数</span></span><br><span class="line">           <span class="keyword">int</span> columnCount = resultSetMetaData.getColumnCount();</span><br><span class="line">           <span class="comment">//创建集合对象</span></span><br><span class="line">           ArrayList&lt;T&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">           <span class="keyword">while</span> (resultSet.next())&#123;</span><br><span class="line">               T t = clazz.newInstance();</span><br><span class="line">               <span class="comment">//处理结果集数据中的每一个列：给t对象指定的属性赋值</span></span><br><span class="line">               <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; columnCount;i++) &#123;</span><br><span class="line">                   <span class="comment">//获取列值</span></span><br><span class="line">                   Object columvalue = resultSet.getObject(i + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">                   <span class="comment">//获取某个列的列名</span></span><br><span class="line">                   String columnName = resultSetMetaData.getColumnName(i+<span class="number">1</span>);</span><br><span class="line">                   <span class="comment">//给customer对象指定的某个属性，赋值为value</span></span><br><span class="line">                   <span class="comment">//给customer对象指定的columnName属性，赋值为columvalues,通过反射</span></span><br><span class="line">                   Field field = clazz.getDeclaredField(columnName);</span><br><span class="line">                   field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                   field.set(t,columvalue);</span><br><span class="line">               &#125;</span><br><span class="line">               list.add(t);</span><br><span class="line">           &#125;</span><br><span class="line">           <span class="keyword">return</span> list;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           closeResource1(connection,preparedStatement,resultSet);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<p>通用特殊值查询</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//通用特殊值查询</span></span><br><span class="line">   <span class="keyword">public</span> &lt;E&gt; <span class="function">E <span class="title">getValue</span><span class="params">(Connection connection,String sql,Object...args)</span>  </span>&#123;</span><br><span class="line">       PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">       ResultSet resultSet = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">           <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt;args.length;i++)&#123;</span><br><span class="line">               preparedStatement.setObject(i + <span class="number">1</span>,args[i]);</span><br><span class="line"></span><br><span class="line">           &#125;</span><br><span class="line">           resultSet = preparedStatement.executeQuery();</span><br><span class="line">           <span class="keyword">if</span> (resultSet.next())&#123;</span><br><span class="line">               <span class="keyword">return</span> (E) resultSet.getObject(<span class="number">1</span>);</span><br><span class="line">           &#125;</span><br><span class="line">       &#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           JDBC.closeResource1(<span class="keyword">null</span>,preparedStatement,resultSet);</span><br><span class="line">       &#125;</span><br><span class="line">       <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>



<h4 id="1-3-3-4-插入图片"><a href="#1-3-3-4-插入图片" class="headerlink" title="1.3.3.4 插入图片"></a>1.3.3.4 插入图片</h4><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testInsert</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">       Connection connection = JDBC.getConnection1();</span><br><span class="line">       String sql = <span class="string">"insert into student(id,photo)values (?,?)"</span>;</span><br><span class="line">       PreparedStatement preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">       preparedStatement.setObject(<span class="number">1</span>,<span class="number">4</span>);</span><br><span class="line">       FileInputStream is = <span class="keyword">new</span> FileInputStream(<span class="string">"F:\\red-pagoda-temple-3380967.jpg"</span>);</span><br><span class="line">       preparedStatement.setBlob(<span class="number">2</span>,is);</span><br><span class="line">       preparedStatement.execute();</span><br><span class="line">       JDBC.closeResource1(connection,preparedStatement,<span class="keyword">null</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-3-4Statement和PreparedStatement区别"><a href="#1-3-4Statement和PreparedStatement区别" class="headerlink" title="1.3.4Statement和PreparedStatement区别"></a>1.3.4Statement和PreparedStatement区别</h3><ul>
<li>解决了Statement的拼串</li>
<li>解决了SQL注入问题</li>
<li>PreparedStatement可以操作Blob的数据</li>
<li>PreparedStatement可以实现更高效的批量操作</li>
</ul>
<h2 id="1-4-批量插入"><a href="#1-4-批量插入" class="headerlink" title="1.4 批量插入"></a>1.4 批量插入</h2><ul>
<li><p>ddBatch()     excuteBatch()     clearBatch()</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//设置不允许自动提交数据</span></span><br><span class="line">         conn.setAutoCommit(<span class="keyword">false</span>);</span><br><span class="line">         <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>;i &lt;= <span class="number">10000</span>;i++)&#123;</span><br><span class="line">             <span class="comment">//1.攒SQL</span></span><br><span class="line">             ps.addBatch();</span><br><span class="line">             <span class="keyword">if</span> (i % <span class="number">500</span> == <span class="number">0</span>)&#123;</span><br><span class="line">                 <span class="comment">//2.执行batch</span></span><br><span class="line">                 ps.executeBatch();</span><br><span class="line">                 <span class="comment">//3.清空batch</span></span><br><span class="line">                 ps.clearBatch();</span><br><span class="line">             &#125;</span><br><span class="line">         &#125;</span><br><span class="line">         <span class="comment">//4.统一提交</span></span><br><span class="line">         conn.commit();</span><br></pre></td></tr></table></figure>



</li>
</ul>
<ul>
<li><p>mysql服务器默认关闭批处理，修改参数,写在配置文件url的后面  </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">?rewriteBetchedStatements&#x3D;true</span><br></pre></td></tr></table></figure>
</li>
<li><p>不允许自动提交</p>
</li>
</ul>
<h2 id="1-5-事务"><a href="#1-5-事务" class="headerlink" title="1.5 事务"></a>1.5 事务</h2><ul>
<li>当一个事务中执行多个操作时，要么所有的事物==都被提交==，要么放弃所有修改，==整个事务回滚==到最初的状态</li>
<li>数据一旦提交就不可回滚</li>
<li>当一个连接被创建时，默认情况下是自动提交事务</li>
<li>关闭数据库连接，数据就会自动提交</li>
<li>DDL操作一旦执行，都会自动提交，set autocommit = false对DDL不起作用</li>
<li>DML默认情况下，一旦执行，就会自动提交，可以通过 set autocommit = false取消自动提交</li>
<li>使用后需要恢复自动提交状态</li>
</ul>
<h3 id="1-5-1-考虑事务通用的增删改"><a href="#1-5-1-考虑事务通用的增删改" class="headerlink" title="1.5.1 考虑事务通用的增删改"></a>1.5.1 考虑事务通用的增删改</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//模拟转账</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testWithTx</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        Connection connection = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            connection = JDBC.getConnection1();</span><br><span class="line">            System.out.println(connection.getAutoCommit());</span><br><span class="line">            <span class="comment">//1.取消数据自动提交</span></span><br><span class="line">            connection.setAutoCommit(<span class="keyword">false</span>);</span><br><span class="line">            <span class="comment">//操作一</span></span><br><span class="line">            String sql1 = <span class="string">"update user_table set balance = balance - 100 where user = ?"</span>;</span><br><span class="line">            update(connection,sql1,<span class="string">"AA"</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//模拟网络异常</span></span><br><span class="line"><span class="comment">//            System.out.println(10/0);</span></span><br><span class="line">            <span class="comment">//操作二</span></span><br><span class="line">            String sql2 = <span class="string">"update user_table set balance = balance + 100 where user = ?"</span>;</span><br><span class="line">            update(connection,sql2,<span class="string">"BB"</span>);</span><br><span class="line"></span><br><span class="line">            <span class="comment">//2.提交数据</span></span><br><span class="line">            connection.commit();</span><br><span class="line">            System.out.println(<span class="string">"转账成功"</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">            <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//3.回滚数据</span></span><br><span class="line">                connection.rollback();</span><br><span class="line">                System.out.println(<span class="string">"转账失败"</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (SQLException ex) &#123;</span><br><span class="line">                ex.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">             <span class="keyword">try</span> &#123;</span><br><span class="line">                <span class="comment">//恢复自动提交状态</span></span><br><span class="line">                connection.setAutoCommit(<span class="keyword">true</span>);</span><br><span class="line">            &#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">                e.printStackTrace();</span><br><span class="line">            &#125;</span><br><span class="line">            JDBC.closeResource1(connection,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">update</span><span class="params">(Connection connection,String sql, Object ...args)</span> </span>&#123;</span><br><span class="line"><span class="comment">//        Connection connection = null ;</span></span><br><span class="line">        PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//1.连接数据库</span></span><br><span class="line"><span class="comment">//            connection = JDBC.getConnection1();</span></span><br><span class="line">            <span class="comment">//2.预编译的SQL语句，返回PreparedStatement实例</span></span><br><span class="line">            preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">            <span class="comment">//3.填充占位符</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length;i++)&#123;</span><br><span class="line">                preparedStatement.setObject(i + <span class="number">1</span>,args[i]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//4.执行</span></span><br><span class="line">            preparedStatement.execute();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line">           </span><br><span class="line">            <span class="comment">//5.关闭资源</span></span><br><span class="line">            JDBC.closeResource1(<span class="keyword">null</span>,preparedStatement,<span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-5-2-事务的ACID属性"><a href="#1-5-2-事务的ACID属性" class="headerlink" title="1.5.2 事务的ACID属性"></a>1.5.2 事务的ACID属性</h3><ol>
<li>原子性</li>
<li>一致性</li>
<li>隔离性</li>
<li>持久性</li>
</ol>
<h3 id="1-5-3-数据库的并发"><a href="#1-5-3-数据库的并发" class="headerlink" title="1.5.3 数据库的并发"></a>1.5.3 数据库的并发</h3><ul>
<li>脏读</li>
<li>不可重复读</li>
<li>幻读</li>
</ul>
<h3 id="1-5-4-四种隔离级别"><a href="#1-5-4-四种隔离级别" class="headerlink" title="1.5.4 四种隔离级别"></a>1.5.4 四种隔离级别</h3><ol>
<li>READ UNCOMMITTED    (读未提交数据)</li>
<li>READ COMMITED    (读已提交数据)</li>
<li>REPEATABLE READ    (可重复读)</li>
<li>SERIALIZABLE    (序列化)</li>
</ol>
<h2 id="1-6-升级操作"><a href="#1-6-升级操作" class="headerlink" title="1.6 升级操作"></a>1.6 升级操作</h2><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">CustomerImpl</span> <span class="keyword">extends</span> <span class="title">BaseDAO</span>&lt;<span class="title">Customer</span>&gt; <span class="keyword">implements</span> <span class="title">CustomerDAO</span></span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span>  <span class="keyword">abstract</span> <span class="class"><span class="keyword">class</span> <span class="title">BaseDAO</span>&lt;<span class="title">T</span>&gt; </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> Class&lt;T&gt; clazz = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    &#123;</span><br><span class="line">        <span class="comment">//获取当前BaseDAO的子类继承的父类中的泛型</span></span><br><span class="line">        Type genericSuperclass = <span class="keyword">this</span>.getClass().getGenericSuperclass();</span><br><span class="line">        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;</span><br><span class="line">        Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();<span class="comment">//获取了父类的泛型参数</span></span><br><span class="line">        clazz = (Class&lt;T&gt;) actualTypeArguments[<span class="number">0</span>];</span><br><span class="line">    &#125;</span><br><span class="line">	<span class="comment">//通用的增删改</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">update</span><span class="params">(Connection connection, String sql, Object ...args)</span> </span>&#123;</span><br><span class="line"><span class="comment">//        Connection connection = null ;</span></span><br><span class="line">        PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="comment">//1.连接数据库</span></span><br><span class="line"><span class="comment">//            connection = JDBC.getConnection1();</span></span><br><span class="line">            <span class="comment">//2.预编译的SQL语句，返回PreparedStatement实例</span></span><br><span class="line">            preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">            <span class="comment">//3.填充占位符</span></span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length;i++)&#123;</span><br><span class="line">                preparedStatement.setObject(i + <span class="number">1</span>,args[i]);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="comment">//4.执行</span></span><br><span class="line">            preparedStatement.execute();</span><br><span class="line"></span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;<span class="keyword">finally</span> &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">            <span class="comment">//5.关闭资源</span></span><br><span class="line">            JDBC.closeResource1(<span class="keyword">null</span>,preparedStatement,<span class="keyword">null</span>);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">//通用查询</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span>  List&lt;T&gt; <span class="title">query2</span><span class="params">(Connection connection, String sql, Object...args)</span> </span>&#123;</span><br><span class="line"><span class="comment">//        Connection connection = null;</span></span><br><span class="line">        PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">        ResultSet resultSet = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line"><span class="comment">//            connection = JDBC.getConnection1();</span></span><br><span class="line">            preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; args.length; i++)&#123;</span><br><span class="line">                preparedStatement.setObject(i + <span class="number">1</span>, args[i]);</span><br><span class="line">            &#125;</span><br><span class="line">            resultSet = preparedStatement.executeQuery();</span><br><span class="line">            <span class="comment">//获取结果集的数据元</span></span><br><span class="line">            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();</span><br><span class="line">            <span class="comment">//获取结果集的列数</span></span><br><span class="line">            <span class="keyword">int</span> columnCount = resultSetMetaData.getColumnCount();</span><br><span class="line">            <span class="comment">//创建集合对象</span></span><br><span class="line">            ArrayList&lt;T&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">            <span class="keyword">while</span> (resultSet.next())&#123;</span><br><span class="line">                T t = clazz.newInstance();</span><br><span class="line">                <span class="comment">//处理结果集数据中的每一个列：给t对象指定的属性赋值</span></span><br><span class="line">                <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt; columnCount;i++) &#123;</span><br><span class="line">                    <span class="comment">//获取列值</span></span><br><span class="line">                    Object columvalue = resultSet.getObject(i + <span class="number">1</span>);</span><br><span class="line"></span><br><span class="line">                    <span class="comment">//获取某个列的列名</span></span><br><span class="line">                    String columnName = resultSetMetaData.getColumnName(i+<span class="number">1</span>);</span><br><span class="line">                    <span class="comment">//给customer对象指定的某个属性，赋值为value</span></span><br><span class="line">                    <span class="comment">//给customer对象指定的columnName属性，赋值为columvalues,通过反射</span></span><br><span class="line">                    Field field = clazz.getDeclaredField(columnName);</span><br><span class="line">                    field.setAccessible(<span class="keyword">true</span>);</span><br><span class="line">                    field.set(t,columvalue);</span><br><span class="line">                &#125;</span><br><span class="line">                list.add(t);</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> list;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            JDBC.closeResource1(connection,preparedStatement,resultSet);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//通用特殊值查询</span></span><br><span class="line">    <span class="keyword">public</span> &lt;E&gt; <span class="function">E <span class="title">getValue</span><span class="params">(Connection connection,String sql,Object...args)</span>  </span>&#123;</span><br><span class="line">        PreparedStatement preparedStatement = <span class="keyword">null</span>;</span><br><span class="line">        ResultSet resultSet = <span class="keyword">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            preparedStatement = connection.prepareStatement(sql);</span><br><span class="line">            <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>;i &lt;args.length;i++)&#123;</span><br><span class="line">                preparedStatement.setObject(i + <span class="number">1</span>,args[i]);</span><br><span class="line"></span><br><span class="line">            &#125;</span><br><span class="line">            resultSet = preparedStatement.executeQuery();</span><br><span class="line">            <span class="keyword">if</span> (resultSet.next())&#123;</span><br><span class="line">                <span class="keyword">return</span> (E) resultSet.getObject(<span class="number">1</span>);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; <span class="keyword">catch</span> (SQLException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            JDBC.closeResource1(<span class="keyword">null</span>,preparedStatement,resultSet);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-7-数据库连接池"><a href="#1-7-数据库连接池" class="headerlink" title="1.7 数据库连接池"></a>1.7 数据库连接池</h2><h3 id="1-7-1-德鲁伊（druid）"><a href="#1-7-1-德鲁伊（druid）" class="headerlink" title="1.7.1 德鲁伊（druid）"></a>1.7.1 德鲁伊（druid）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">DruidTest</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> DataSource source;</span><br><span class="line">    <span class="keyword">static</span> &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            Properties pros = <span class="keyword">new</span> Properties();</span><br><span class="line">            InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(<span class="string">"druid"</span>);</span><br><span class="line">            pros.load(is);</span><br><span class="line">            source = DruidDataSourceFactory.createDataSource(pros);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Connection <span class="title">getConnection</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">        Connection connection = source.getConnection();</span><br><span class="line">        System.out.println(connection);</span><br><span class="line">        <span class="keyword">return</span> connection;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="1-8-DBUtils"><a href="#1-8-DBUtils" class="headerlink" title="1.8 DBUtils"></a>1.8 DBUtils</h2><figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- https://mvnrepository.com/artifact/commons-dbutils/commons-dbutils --&gt;</span></span><br><span class="line">   <span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-dbutils<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-dbutils<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">     <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.7<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="1-8-1-增删改"><a href="#1-8-1-增删改" class="headerlink" title="1.8.1 增删改"></a>1.8.1 增删改</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testQueryRunner</span><span class="params">()</span> <span class="keyword">throws</span> Exception </span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           QueryRunner runner = <span class="keyword">new</span> QueryRunner();</span><br><span class="line">           connection = DruidTest.getConnection();</span><br><span class="line">           String sql = <span class="string">"insert into customers(id,name ,email ,birth)values(?,?,?,?)"</span>;</span><br><span class="line">           <span class="keyword">int</span> insertCount = runner.update(connection, sql, <span class="string">"6"</span>,<span class="string">"蔡徐坤"</span>, <span class="string">"caixukun@qq.com"</span>, <span class="string">"1997-01-01"</span>);</span><br><span class="line">           System.out.println(<span class="string">"添加了"</span>+insertCount+<span class="string">"条数据"</span>);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           JDBC.closeResource1(connection,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-8-2-查询（返回一条记录）"><a href="#1-8-2-查询（返回一条记录）" class="headerlink" title="1.8.2 查询（返回一条记录）"></a>1.8.2 查询（返回一条记录）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testQuery1</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           QueryRunner runner = <span class="keyword">new</span> QueryRunner();</span><br><span class="line">           connection = DruidTest.getConnection();</span><br><span class="line">           String sql = <span class="string">"select id,name,email from customers where id = ?"</span>;</span><br><span class="line">           BeanHandler&lt;Customer&gt; handler = <span class="keyword">new</span> BeanHandler&lt;&gt;(Customer<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">           Customer customer = runner.query(connection, sql, handler, <span class="number">5</span>);</span><br><span class="line">           System.out.println(customer);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           JDBC.closeResource1(connection,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<ul>
<li>BeanHandler：是ResultBeanHandler接口的实现类，用于封装表中的一条记录</li>
</ul>
<h3 id="1-8-3-查询（返回多条记录）"><a href="#1-8-3-查询（返回多条记录）" class="headerlink" title="1.8.3 查询（返回多条记录）"></a>1.8.3 查询（返回多条记录）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testQuery2</span><span class="params">()</span> <span class="keyword">throws</span> Exception</span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           QueryRunner runner = <span class="keyword">new</span> QueryRunner();</span><br><span class="line">           connection = DruidTest.getConnection();</span><br><span class="line">           String sql = <span class="string">"select id,name,email from customers where id &lt; ?"</span>;</span><br><span class="line">           BeanListHandler&lt;Customer&gt; handler = <span class="keyword">new</span> BeanListHandler&lt;&gt;(Customer<span class="class">.<span class="keyword">class</span>)</span>;</span><br><span class="line">           List&lt;Customer&gt; list = runner.query(connection, sql, handler, <span class="number">5</span>);</span><br><span class="line">           list.forEach(System.out::println);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           JDBC.closeResource1(connection,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-8-4-查询（特殊返回值）"><a href="#1-8-4-查询（特殊返回值）" class="headerlink" title="1.8.4 查询（特殊返回值）"></a>1.8.4 查询（特殊返回值）</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">testQuery3</span><span class="params">()</span></span>&#123;</span><br><span class="line">       Connection connection = <span class="keyword">null</span>;</span><br><span class="line">       <span class="keyword">try</span> &#123;</span><br><span class="line">           QueryRunner runner = <span class="keyword">new</span> QueryRunner();</span><br><span class="line">           connection = DruidTest.getConnection();</span><br><span class="line">           String sql = <span class="string">"select count(*) from customers"</span>;</span><br><span class="line">           ScalarHandler handler = <span class="keyword">new</span> ScalarHandler();</span><br><span class="line">           Long count = (Long) runner.query(connection, sql, handler);</span><br><span class="line">           System.out.println(count);</span><br><span class="line">       &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">           e.printStackTrace();</span><br><span class="line">       &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">           JDBC.closeResource1(connection,<span class="keyword">null</span>,<span class="keyword">null</span>);</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>

<h3 id="1-8-5-关闭资源"><a href="#1-8-5-关闭资源" class="headerlink" title="1.8.5 关闭资源"></a>1.8.5 关闭资源</h3><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">closeResources</span><span class="params">(Connection connection, Statement statement, ResultSet resultSet)</span> </span>&#123;</span><br><span class="line">       DbUtils.closeQuietly(connection);</span><br><span class="line">       DbUtils.closeQuietly(statement);</span><br><span class="line">       DbUtils.closeQuietly(resultSet);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure>


      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>呐呐呐，赏点吧</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/wechatpay.png" alt="孤失狐 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.png" alt="孤失狐 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Java/" rel="tag"><i class="fa fa-tag"></i> Java</a>
          
            <a href="/tags/%E6%95%B0%E6%8D%AE%E5%BA%93/" rel="tag"><i class="fa fa-tag"></i> 数据库</a>
          
            <a href="/tags/JDBC/" rel="tag"><i class="fa fa-tag"></i> JDBC</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2020/02/29/hello-world/" rel="next" title="Hello World">
                <i class="fa fa-chevron-left"></i> Hello World
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2020/03/08/SpringMVC/" rel="prev" title="SpringMVC">
                SpringMVC <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/ChatHead.jpg"
                alt="孤失狐" />
            
              <p class="site-author-name" itemprop="name">孤失狐</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/%7C%7C%20archive">
              
                  <span class="site-state-item-count">8</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">1</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">4</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/gushihu1" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://space.bilibili.com/183711782" target="_blank" title="Bilibili">
                      
                        <i class="fa fa-fw fa-bilibili"></i>Bilibili</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="http://yangbin1215.gitee.io/" title="杨彬的码云博客" target="_blank">杨彬的码云博客</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="https://yangbin1215.github.io/" title="杨彬的GitHub博客" target="_blank">杨彬的GitHub博客</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-3"><a class="nav-link" href="#摘要"><span class="nav-number">1.</span> <span class="nav-text">摘要</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#JDBC"><span class="nav-number"></span> <span class="nav-text">JDBC</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1获取连接"><span class="nav-number"></span> <span class="nav-text">1.1获取连接</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-1-配置文件获取连接"><span class="nav-number">1.</span> <span class="nav-text">1.1.1 配置文件获取连接</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-关闭资源"><span class="nav-number"></span> <span class="nav-text">1.2 关闭资源</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-3-PreparedStatement和Statement"><span class="nav-number"></span> <span class="nav-text">1.3 PreparedStatement和Statement</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-1-Statement存在的问题"><span class="nav-number">1.</span> <span class="nav-text">1.3.1 Statement存在的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-2-Statement对数据库进行操作"><span class="nav-number">2.</span> <span class="nav-text">1.3.2 Statement对数据库进行操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-3-PreparedStatement对数据库进行操作"><span class="nav-number">3.</span> <span class="nav-text">1.3.3 PreparedStatement对数据库进行操作</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-3-1-增删改"><span class="nav-number">3.1.</span> <span class="nav-text">1.3.3.1 增删改</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-3-2-通用的增删改"><span class="nav-number">3.2.</span> <span class="nav-text">1.3.3.2 通用的增删改</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-3-3-通用查询"><span class="nav-number">3.3.</span> <span class="nav-text">1.3.3.3 通用查询</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-3-3-1-返回表中的一条数据"><span class="nav-number">3.3.1.</span> <span class="nav-text">1.3.3.3.1 返回表中的一条数据</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-3-3-2-返回多行数据"><span class="nav-number">3.3.2.</span> <span class="nav-text">1.3.3.3.2 返回多行数据</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#1-3-3-3-3-查所有"><span class="nav-number">3.3.3.</span> <span class="nav-text">1.3.3.3.3 查所有</span></a></li></ol></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-3-3-4-插入图片"><span class="nav-number">3.4.</span> <span class="nav-text">1.3.3.4 插入图片</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-4Statement和PreparedStatement区别"><span class="nav-number">4.</span> <span class="nav-text">1.3.4Statement和PreparedStatement区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-4-批量插入"><span class="nav-number"></span> <span class="nav-text">1.4 批量插入</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-5-事务"><span class="nav-number"></span> <span class="nav-text">1.5 事务</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-1-考虑事务通用的增删改"><span class="nav-number">1.</span> <span class="nav-text">1.5.1 考虑事务通用的增删改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-2-事务的ACID属性"><span class="nav-number">2.</span> <span class="nav-text">1.5.2 事务的ACID属性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-3-数据库的并发"><span class="nav-number">3.</span> <span class="nav-text">1.5.3 数据库的并发</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-5-4-四种隔离级别"><span class="nav-number">4.</span> <span class="nav-text">1.5.4 四种隔离级别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-6-升级操作"><span class="nav-number"></span> <span class="nav-text">1.6 升级操作</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-7-数据库连接池"><span class="nav-number"></span> <span class="nav-text">1.7 数据库连接池</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-7-1-德鲁伊（druid）"><span class="nav-number">1.</span> <span class="nav-text">1.7.1 德鲁伊（druid）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-8-DBUtils"><span class="nav-number"></span> <span class="nav-text">1.8 DBUtils</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-8-1-增删改"><span class="nav-number">1.</span> <span class="nav-text">1.8.1 增删改</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-8-2-查询（返回一条记录）"><span class="nav-number">2.</span> <span class="nav-text">1.8.2 查询（返回一条记录）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-8-3-查询（返回多条记录）"><span class="nav-number">3.</span> <span class="nav-text">1.8.3 查询（返回多条记录）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-8-4-查询（特殊返回值）"><span class="nav-number">4.</span> <span class="nav-text">1.8.4 查询（特殊返回值）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-8-5-关闭资源"><span class="nav-number">5.</span> <span class="nav-text">1.8.5 关闭资源</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">孤失狐</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

<script src="/live2dw/lib/L2Dwidget.min.js?094cbace49a39548bed64abff5988b05"></script><script>L2Dwidget.init({"pluginRootPath":"live2dw/","pluginJsPath":"lib/","pluginModelPath":"assets/","tagMode":false,"debug":false,"model":{"jsonPath":"/live2dw/assets/shizuku.model.json"},"display":{"position":"left","width":150,"height":300},"mobile":{"show":true},"react":{"opacity":1},"log":false});</script></body>
</html>
